package com.woniuxy.shop.Service.Serviceimpl;

import com.hc.entity.*;
import com.woniuxy.shop.Entity.ChartData;
import com.woniuxy.shop.Entity.ResponseEntity;
import com.woniuxy.shop.Entity.Serie;
import com.woniuxy.shop.Mapper.LLMapper;
import com.woniuxy.shop.Service.LLService;
import com.woniuxy.shop.util.SimpleRedisLock;
import org.springframework.aop.framework.AopContext;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

/**
 * @ClassName LLService
 * @Description
 * @Author ll
 * @Date 2022/10/19 15:38
 * @Version 1.0
 **/
@Service("LLService")
public class LLServiceimpl implements LLService {
    @Autowired
    LLMapper llMapper;

    @Resource
    StringRedisTemplate stringRedisTemplate;
    public static int getDaysOfMonth(Date date) {
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(date);
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
    }
    private static String getFirstday(String date1) throws ParseException {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Date date = new Date();
        date= new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date1);
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(date);
        calendar.add(Calendar.MONTH, 0);
        calendar.set(Calendar.DAY_OF_MONTH, 1);
        String firstDay = sdf.format(calendar.getTime());
        System.out.println("firstDay:"+ firstDay);
        return firstDay;
    }
    @Override
    public boolean isexitshop(int id) {
        Shop isexitshop = llMapper.isexitshop(id);
        boolean result = isexitshop==null;
        return result;
    }

    @Override
    public void insertshop(Shop shop) {
        shop.setStatus("x");
        llMapper.insertshop(shop);
    }

    @Override
    public boolean ispass(int id) {
        Shop ispass = llMapper.ispass(id);
        boolean result = ispass==null;
        return result;
    }

    @Override
    public void insertgoods(Goods goods) {
        goods.setStatus("n");
        llMapper.insertgoods(goods);
    }

    @Override
    public List<Goods> getmygoods(int id) {
        Shop ispass = llMapper.ispass(id);
        List<Goods> getmygoods = llMapper.getmygoods(5);
        return getmygoods;
    }

    @Override
    public Goods getgoodsdetail(int id) {
        Goods getgoodsdetail = llMapper.getgoodsdetail(id);
        return getgoodsdetail;
    }

    @Override
    public void changestock(int id, int stock) {
        llMapper.changestock(id,stock);
    }

    @Override
    public void offyheshelf(int id) {
        llMapper.offyheshelf(id);
    }

    @Override
    public List<Order> finish(int shopid) {
        List<Order> finish = llMapper.finish(shopid);
        return finish;
    }

    @Override
    public List<Order> allorder(int shopid) {
        List<Order> allorder = llMapper.allorder(shopid);
        return allorder;

    }

    @Override
    public List<Order> notfinish(int shopid) {
        List<Order> finish = llMapper.notfinish(shopid);
        return finish;
    }

    @Override
    public void addsecondkill(Seckill seckill) {
        llMapper.addsecondkill(seckill);
    }

    @Override
    public void addGoodsDiscountMid(int discount, int goodsId) {
        llMapper.addGoodsDiscountMid(discount,goodsId);
    }

    @Override
    public void addDiscountType(DiscountType discountType,int goodsid) {
        GoodsDiscountMid goodsDiscountMid = new GoodsDiscountMid();
        goodsDiscountMid.setGoodsId(goodsid);
        llMapper.addDiscountType(discountType);
        llMapper.addGoodsDiscountMid(discountType.getId(),goodsid);
    }

    @Override
    public void dayang(int shopid) {
        llMapper.dayang(shopid);
    }

    @Override
    public void openshop(int shopid) {
        llMapper.openshop(shopid);
    }

    @Override
    public Shop getshopstatus(int id) {
        return llMapper.getshopstatus(id);
    }

    @Override
    public BigDecimal today(String date,int id) throws ParseException {
        List<Order> finishs = llMapper.finish(id);
        Date date1 = new Date();
        date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
        BigDecimal totalmoney=new BigDecimal(0);
        for (Order finish : finishs) {
            String ordertime = finish.getOrdertime();
            Date date2 = new Date();
            date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ordertime);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
            boolean equals = fmt.format(date1).equals(fmt.format(date2));
            if(equals){
                BigDecimal payment = finish.getPayment();
                totalmoney=totalmoney.add(payment);
            }
        }
        System.out.println(totalmoney);
        return totalmoney;
    }

    @Override
    public BigDecimal month(String date, int id) throws ParseException {
        List<Order> finishs = llMapper.finish(id);
        Date date1 = new Date();
        date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(date);
        BigDecimal totalmoney=new BigDecimal(0);
        for (Order finish : finishs) {
            String ordertime = finish.getOrdertime();
            Date date2 = new Date();
            date2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(ordertime);
            SimpleDateFormat fmt = new SimpleDateFormat("yyyyMM");
            boolean equals = fmt.format(date1).equals(fmt.format(date2));
            if(equals){
                BigDecimal payment = finish.getPayment();
                totalmoney=totalmoney.add(payment);
            }
        }
        System.out.println(totalmoney);
        return totalmoney;
    }

    @Override
    public ChartData getChartData(String date, int shopid) throws ParseException {
        String firstday = getFirstday(date);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        int daysOfMonth = getDaysOfMonth(sdf.parse(date));
//        Integer month = getMonth(date11);
//        System.out.println("month:"+ month);
        List<BigDecimal> data= new ArrayList<>();
        List<Integer> categories = new ArrayList<>();
        for(int i=1;i<=daysOfMonth;i++){
            categories.add(i);
            BigDecimal day= new BigDecimal(0);
            List<Order> finish = llMapper.finish(shopid);
            String s="";
            if(i<10){
                s=firstday.substring(0,firstday.length()-1)+i;
            } else if (i>=10) {
                s=firstday.substring(0,firstday.length()-2)+i;
            }
            System.out.println(s);
            Date date11 = new Date();
            date11 = new SimpleDateFormat("yyyy-MM-dd").parse(s);
            for (Order order : finish) {
                String data2=order.getOrdertime();
                Date date22 = new Date();
                date22 = new SimpleDateFormat("yyyy-MM-dd").parse(data2);
                SimpleDateFormat fmt = new SimpleDateFormat("yyyyMMdd");
                boolean equals = fmt.format(date11).equals(fmt.format(date22));
                if(equals){
                    System.out.println("有的:"+date22);
                    day=day.add(order.getPayment());
                }
            }
            data.add(day);
        }
        ChartData chartData=new ChartData();
        chartData.setCategories(categories);
        Serie serie=new Serie();
        serie.setName("本月营业");
        serie.setData(data);
        List<Serie> series=new ArrayList<>();
        series.add(serie);
        chartData.setSeries(series);
        return chartData;
    }

    @Override
    public Order getorder(int id) {
        return llMapper.getorder(id);
    }

    @Override
    public void checkorder(int id) {
        llMapper.checkorder(id);
    }

    @Override
    @Transactional
    public ResponseEntity secondkill(int id) {
        //查询秒杀信息
        Seckill getsecondkill = llMapper.getsecondkill(id);
        String startTime = getsecondkill.getStartTime();
        String endTime = getsecondkill.getEndTime();

        //判断是否超前
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime parsedDate = LocalDateTime.parse(startTime, formatter);
        LocalDateTime parsedDate1 = LocalDateTime.parse(endTime, formatter);
        //判断活动是否开始
        ResponseEntity result=new ResponseEntity<>();
        if (parsedDate.isAfter(LocalDateTime.now())) {
            result.setCode("204");
            result.setMsg("活动未开始");
            return result;
        }
        //判断是否已经结束
        if(parsedDate1.isBefore(LocalDateTime.now())){
            result.setCode("205");
            result.setMsg("活动已结束");
            return result;
        }
        //判断库存是否充足

//        try {
//            Thread.sleep(50);
//        } catch (InterruptedException e) {
//            throw new RuntimeException(e);
//        }
        if(getsecondkill.getNum()<1){
            result.setCode("206");
            result.setMsg("库存不足");
            return result;
        }
        //一人一单
        Long userid = Long.valueOf(1);
        String s1="1";
        SimpleRedisLock simpleRedisLock=new SimpleRedisLock("order",stringRedisTemplate);
        boolean b = simpleRedisLock.tryLock(1200);
        if(!b){
            result.setCode("207");
            result.setMsg("不允许重复下单");
            return result;
        }
        try{
            //        //仅仅单机模式使用synchronized
//        synchronized (s1.intern()){
            //获取代理对象,防止事务失效
            LLService llService = (LLService) AopContext.currentProxy();
            return llService.yiren(getsecondkill);
//        }
        }finally {
            simpleRedisLock.unlock();
        }


    }
    @Transactional
    public  ResponseEntity  yiren(Seckill getsecondkill){
        ResponseEntity result=new ResponseEntity<>();
        Integer goodsId = getsecondkill.getGoodsId();
        Goods getgoodsdetail = llMapper.getgoodsdetail(goodsId);
        int getcount = llMapper.getcount(1, getsecondkill.getId());
        if(getcount>0){
            result.setCode("207");
            result.setMsg("用户已经购买");
            return result;
        }
        //更新库存
        llMapper.seckilltock(getsecondkill.getId(),getsecondkill.getNum());
        //创建订单
        Order order=new Order();
        order.setGoodsId(goodsId);
        order.setNum(1);
        String s = LocalDateTime.now().toString();
        order.setOrdertime(s);
        order.setPayment(getsecondkill.getSecprice());
        order.setOriginalprice(getgoodsdetail.getPrice());
        order.setUserId(1);
        order.setStatus("p");
        order.setSecondkillid(getsecondkill.getId());
        order.setShopId(getgoodsdetail.getShopId());
        llMapper.addorder(order);
        result.setCode("200");
        result.setMsg("成功");
        result.setData(order.getId());
        return result;
    }
}